package com.itheima.tilas.aspect;

import com.itheima.tilas.Utils.JwtUtil;
import com.itheima.tilas.mapper.EmpMapper;
import com.itheima.tilas.mapper.LogMapper;
import com.itheima.tilas.po.InsertEmpOneParam;
import com.itheima.tilas.po.InsertLogParam;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;


/**
 * 日志切面类
 *  @author 132
 * @Aspect 标志切面类
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    @Resource
    LogMapper logMapper;
    @Resource
    EmpMapper empMapper;
    @Resource
    HttpServletRequest request;
    @Around("@annotation(com.itheima.tilas.annotation.Log)")
    public Object insertLog(ProceedingJoinPoint joinPoint){
        InsertLogParam logParam = new InsertLogParam();
        String token = request.getHeader("token");
        String username = JwtUtil.verifyToken(token).getString("username");
        int id = empMapper.selectEmpByUsername(username).getId();
        logParam.setOperateEmpId(id);
        long start = System.currentTimeMillis();
        try {
            Object proceed = joinPoint.proceed();
            logParam.setOperateTime(LocalDateTime.now());
            long end = System.currentTimeMillis() - start;
            logParam.setCostTime((int) end);
            logParam.setClassName(joinPoint.getTarget().toString().split("@")[0]);
            logParam.setMethodName(joinPoint.getSignature().getName());
            logParam.setMethodParams(Arrays.toString(joinPoint.getArgs()));
            logParam.setReturnValue(joinPoint.proceed().toString());
            logMapper.insertLogOne(logParam);
            log.info("插入日志{}",joinPoint.getSignature().getName());
            return proceed;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
